package dm.ast;

import test.envset.GlobalState;

public class DmTop extends DmASTNode{

    /**
     * select top 1 a from (select 1 as a union select 2 as a)
     * top四种情况：
     * 1、top n: n>=0
     * 2、top n1 , n2:n1,n2
     * 3、top n with ties
     * 4、top n percent:n范围：0-100
     * 5、top n percent with ties
     * @param globalState
     */

    public int m = 0;
    public int n = 0;
    public boolean percentflag;
    public boolean withTiesflag;

    public String toSql(){
        if(m != 0 && n != 0){
            return String.format(" TOP %s" , m + ", " + n);
        }
        if(percentflag && withTiesflag){
            return String.format(" TOP %s" , m + "PERCENT WITH TIES");
        }else if(percentflag){
            return String.format(" TOP %s" , m + "PERCENT");
        }else if(withTiesflag){
            return String.format(" TOP %s" , m + "WITH TIES");
        }else {
            return String.format(" TOP %s" , m );
        }

    }


    @Override
    public void fill(GlobalState globalState) {
        if(!isCompleted){
            if( m != 0){
                isCompleted = true;
            }
        }
    }

    @Override
    public void setWidt() {
        if(m == 0 && n == 0){
            wid_t = 0;
        }else {
            wid_t = 1;
        }
    }

    @Override
    public void setDept() {
        if(m == 0 && n == 0){
            dep_t = 0;
        }else {
            dep_t = 1;
        }
    }

    @Override
    public DmDataType getExpressionType() {
        return null;
    }

    public void fixErr4097(){
        m = 1;
        n = 0;
        percentflag = false;
        withTiesflag = false;
    }
}
